<template>
  <div
    class="w-custom-markdown-parsing"
    v-html="markedown"/>
</template>

<script>
import '@/styles/marked.scss'
import 'highlight.js/styles/xcode.css'
import hljs from 'highlight.js'
import Marked from 'marked'

/**
 * 自定义Markdown编辑器
 */
export default {
  name: 'MarkedCustomSprsing',
  props: {
    /**
     * 传入的MarkDown数据
     */
    datastr: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      /**
       * 解析的数据
       */
      markedown: '',
      /**
       * marked解析对象
       */
      marked: new Marked.Renderer(),
      /**
       * 定时器（缓存数据转换）
       */
      timer: null
    }
  },
  watch: {
    /**
     * 监听数据的改变
     * @param val 新数据
     * @param oldVal 旧数据
     */
    datastr(val, oldVal) {
      this.createTimer(oldVal)
    }
  },
  created() {
    this.initMarked()
  },
  beforeDestroy() {
    this.clearTimer()
  },
  methods: {
    /**
     * 初始化解析对象
     */
    initMarked() {
      const rendererMD = new Marked.Renderer()
      Marked.setOptions({
        renderer: rendererMD,
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: false,
        smartLists: true,
        smartypants: false,
        highlight: function(code) {
          return hljs.highlightAuto(code).value
        }
      })
    },
    /**
     * 创建定时器
     * @param oldVal 旧数据
     */
    createTimer(oldData) {
      if (!oldData) {
        this.markedown = Marked(this.datastr)
        return
      }
      this.clearTimer()
      this.timer = setTimeout(() => {
        this.markedown = Marked(this.datastr)
      }, 500)
    },
    /**
     * 清除定时器
     */
    clearTimer() {
      if (this.timer) {
        clearTimeout(this.timer)
        this.timer = null
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .w-custom-markdown-parsing {
    padding: 0 5px;
    overflow: auto;
  }

</style>
